package com.yetm.springbootdemo.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * websocket测试
 */
@ServerEndpoint(value = "/socket", encoders = ServerEncoder.class)
@Component
public class WsServerEndpoint {
    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println("连接成功");

        show(session);
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭");
    }

    @OnMessage
    public void onMessage(String text) {}

    public void show(Session session) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    Map msg = new HashMap<>();
                    msg.put("status", 1);
                    msg.put("message", 33);
                    if (session.isOpen()) {
                        session.getBasicRemote().sendObject(msg);
                    }
                } catch (IOException | EncodeException e) {
                    e.printStackTrace();
                }
                show(session);
            }
        }, 1000);

    }
}
